<template>
	<div>
		<!-- 商品图片轮播 -->
		<van-swipe class="my-swipe" :autoplay="3000">
			<van-swipe-item v-for="(img,i) in carouselList" :key="i">
				<van-image width="80%" :src="APIDomainName + img" />
			</van-swipe-item>
		</van-swipe>
		<!-- 商品 明细 -->
		<van-cell title="商品编号" :value="product.id" />
		<van-cell title="商品名称" :value="product.name" />
		<van-cell title="商品标题" :value="product.title" />
		<van-cell title="商品规格" :value="product.spec" />
		<van-cell title="硬盘" :value="product.disk" />
		<van-cell title="CPU" :value="product.cpu" />
		<van-cell title="内存" :value="product.memory" />
		<van-cell title="显卡" :value="product.video_card" />
		<van-cell title="分辨率" :value="product.resolution" />
		<van-cell title="上架时间" :value="shelfTime" />
		<van-cell title="单价" :value="product.price" />

		<!-- 商品购买区域 -->
		<van-cell>
			<template #default>
				<div class="count-buy">
					<div>购买数量</div>
					<van-stepper v-model="count" integer />
					<van-button type="primary" size="small" @click="onClickAddShopcart">加入购物车</van-button>
				</div>
			</template>
		</van-cell>

		<van-button type="primary" size="large" @click="onBack">返回</van-button>
	</div>
</template>

<script>
	//1.导入封装后的接口
	//根据id获取商品对象（详情）
	import {
		getProductDetailByIdAPI
	} from "@/api/product.js";

	//导入将商品添加购物车接口
	import {
		addCartAPI
	} from "@/api/cart.js";

	import * as Tools from "@/utils/tools.js"
	export default {
		// 数据
		data() {
			return {
				product: {}, //商品对象（详情）				
				carouselList: [], //商品轮播图片数组				
				count: 0, //步进器绑定的数量
			}
		},
		// 方法
		methods: {
			onBack() {
				this.$router.go(-1)
			},
			//处理添加购物车			
			onClickAddShopcart() {
				let params = {
					product_id: this.product.id,
					count: this.count,
				};
				//2.使用封装后的接口,注意：接口有参数
				addCartAPI(params).then(result => {
					this.$toast(result.msg);
				}).catch((err) => {console.log(err)});
			},
		},
		// 计算属性
		computed: {
			shelfTime() {
				let date = new Date(this.product.shelf_time);
				return Tools.dateFormat(date, "yyyy年MM月dd日");
			}
		},
		// 生命周期钩子-实例创建后,可以用this.*
		created() {
			let id = this.$route.params.id;
			//2.使用封装后的接口
			getProductDetailByIdAPI(id).then(result => {
				console.log(result);
				this.product = result.data //保存API调用的返回数据
				//根据返回数据生成轮播图数组（用商品的中图片）
				this.product.picList.forEach(item => {
					this.carouselList.push(item.md);
				}); //数据的遍历
			});
		},
	}
</script>
<!-- 样式 -->
<style>
	.my-swipe .van-swipe-item {
		color: #fff;
		font-size: 20px;
		line-height: 150px;
		text-align: center;
		/* background-color: #39a9ed; */
	}

	.count-buy {
		display: flex;
		flex-direction: row;
		margin: 10px 0px;
		justify-content: space-between;
	}
</style>
